const Koa = require("koa2");
const cors = require("koa2-cors");
const koajwt = require("koa-jwt");
const path = require("path");
const static = require("koa-static");
const bodyParser = require("koa-bodyparser");

const router = require("./router/index");
const errorHandler = require("./utils/errorHandler.js");

const app = new Koa();
const port = 3000;
const assetsDir = path.join(__dirname, "/assets");
const uploadDir = path.join(__dirname, "/uploads");
const secret = "liuhailang...";

// 处理跨域请求 - 使用更完整的CORS配置
app.use(cors({
  origin: '*',
  allowMethods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
  allowHeaders: ['Content-Type', 'Authorization', 'Accept', 'X-Requested-With'],
  exposeHeaders: ['Content-Disposition', 'Content-Length'],
  credentials: false
}));

// 处理静态资源文件夹
app.use(static(assetsDir, {
  maxage: 30 * 24 * 60 * 60 * 1000, //指定静态资源在浏览器中的缓存时间
}));
app.use(
  static(path.join(assetsDir, "images"), {
    maxage: 30 * 24 * 60 * 60 * 1000,
  })
);

// 访问静态资源文件夹uploads
app.use(static(uploadDir, {
  maxage: 30 * 24 * 60 * 60 * 1000,
}));

// 使用body-parser中间件处理请求体
app.use(
  bodyParser({
    multipart: true,
  })
);

// 拦截需要JWT验证的请求
app.use(
  koajwt({
    secret,
  }).unless({
    // /users/login,/users/reg不需要验证
    path: [
      /^\/users\/login/,
      /^\/users\/reg/,
      /^\/fileUploadDownload\/test/,      // 测试路由
      /^\/fileUploadDownload\/upload-config/, // 上传配置
      /^\/fileUploadDownload\/download/,  // 下载不需要JWT验证
      /^\/fileUploadDownload\/preview/,   // 预览不需要JWT验证
      /^\/fileUploadDownload\/image/,     // 图片访问不需要JWT验证
      /^\/fileUploadDownload\/video/,     // 视频流媒体不需要JWT验证
      /^\/fileUploadDownload\/media/      // 媒体流不需要JWT验证
    ],
    // 静态资源也不需要验证

  })
);

// 注册路由并统一异常处理
app.use(router.routes(), router.allowedMethods());
errorHandler(app);

// 启动服务器
app.listen(port, () => {
  console.log(`服务开启: http://localhost:${port}`);
  console.log(`也可访问: http://192.168.31.222:${port}`);
});
